<?php
namespace Operationtest\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\EventManager\EventManagerInterface;
use Zend\View\Model\ViewModel;
use Operationtest\Classe\WhereQueryBySelection;
use Operationtest\Classe\OperationDate;
use Operationtest\Classe\Table;
use Zend\Session\Container;

class TableaudebordController extends AbstractActionController
{    
    public function setEventManager(EventManagerInterface $events)
    {
        parent::setEventManager($events);
 
        $controller = $this;
        $events->attach('dispatch', function ($e) use ($controller) {
            $controller->layout()->setTemplate('layout/operationtest');
        }, 100);
 
        return $this;
    }
    
    public function indexAction() {
        $table = new Table($sm = $this->getServiceLocator());
        $operationDate = new OperationDate();
        
        $request = $this->getRequest();        
        $tableArray = array(
            'marcheStoreTable' => $table->getMarchestoreTable(),
            'marcheTable' => $table->getMarcheTable(),
            'storeTable' => $table->getStoreTable()
        );
        
        $whereQueryBySelection = new WhereQueryBySelection($tableArray);
        
        if ($request->isPost()) {
            // INITIALIZE PERIOD ///////////////////////////////////////////////////////////////////////////
            $period = $operationDate->displayPeriod($request);
            
            // REAL ///////////////////////////////////////////////////////////////////////////
            $defaultWhere = $whereQueryBySelection->queryForDashboard($request);
            $meteoWhere = $whereQueryBySelection->queryForDashboard($request, 'date', 'Meteo');
            $ecWhere = $whereQueryBySelection->queryForDashboard($request, 'date', 'StoreCount');
            $moWhere = $whereQueryBySelection->queryForDashboard($request, 'date', 'RhData');
            
            // BUDGETS ///////////////////////////////////////////////////////////////////////////
            $budgetWhere = $whereQueryBySelection->budgetQueryForTableauDeBord($request, 'month');
            $budgetResult = $table->getBudgetTable()->getBudgetForTableauDeBord($budgetWhere);
            $budgets = $budgetTmp = array();
            foreach($budgetResult as $budget) {
                $nbOpenDays = $budget->nbWeek1+$budget->nbWeek2+$budget->nbWeek3+$budget->nbWeek4+$budget->nbWeek5+$budget->nbWeek6;
                $budgetTmp[$budget->month][$budget->idStore]['nbOpenDays'] = $nbOpenDays;
                $budgetTmp[$budget->month][$budget->idStore]['totttc'] = $budget->totttc;
                $budgetTmp[$budget->month][$budget->idStore]['tm'] = $budget->tm;
                $budgetTmp[$budget->month][$budget->idStore]['tttxA'] = $budget->txA + $budget->txAl;
                $budgetTmp[$budget->month][$budget->idStore]['txE'] = $budget->txE;
            }
            
            // Récupération du nombre de jours actuels d'ouverture
            $orders = $table->getSaleheadTable()->getNbOpenDays($defaultWhere['month']);
            $nbOpenDays = $this->getNbOpenDays($orders);
            
            $countBudgetTmp = 1;
            foreach($budgetTmp as $idxtmp => $tmp) {
                foreach($tmp as $idstore) {
                    @$budgets['month']['cattc'] += $nbOpenDays[$idxtmp] * $idstore['totttc'];
                    @$budgets['month']['caht'] += (($idstore['totttc']*0.995/1.07)+($idstore['totttc']*0.005/1.196))*$nbOpenDays[$idxtmp];
                    @$budgets['month']['nbt'] += ($idstore['totttc']/$idstore['tm'])*$nbOpenDays[$idxtmp];
                    @$budgets['month']['tttxA'] += $idstore['tttxA'];
                    @$budgets['month']['txE'] += $idstore['txE'];
                    
                    if($countBudgetTmp == count($budgetTmp)) {
                        @$budgets['day']['cattc'] += $idstore['totttc'];
                        @$budgets['day']['caht'] += (($idstore['totttc']*0.995/1.07)+($idstore['totttc']*0.005/1.196));
                        @$budgets['day']['nbt'] += ($idstore['totttc']/$idstore['tm']);
                        @$budgets['day']['tttxA'] += $idstore['tttxA'];
                        @$budgets['day']['txE'] += $idstore['txE'];
                    }
                }
                $countBudgetTmp++;
            }
            
            $dataDashboard = new Container('dataDashboard');
            $dataDashboard->caMonth = $table->getSaleheadTable()->getTbCa($defaultWhere['month']);
            $dataDashboard->caDay = $table->getSaleheadTable()->getTbCa($defaultWhere['day']);
            $dataDashboard->tmMonth = $table->getSaleheadTable()->getTbTmTtc($defaultWhere['month']);
            $dataDashboard->tmDay = $table->getSaleheadTable()->getTbTmTtc($defaultWhere['day']);
            $dataDashboard->meteoMonth = $table->getMeteoTable()->getMeteos($meteoWhere['month']);
            $dataDashboard->meteoDay = $table->getMeteoTable()->getMeteo($meteoWhere['day']);
            $dataDashboard->mealMonth = $table->getSaleheadTable()->getTbRepas($defaultWhere['month']);
            $dataDashboard->mealDay = $table->getSaleheadTable()->getTbRepas($defaultWhere['day']);
            $dataDashboard->nbTMonth = $table->getSaleheadTable()->getTbTransaction($defaultWhere['month']);
            $dataDashboard->nbTDay = $table->getSaleheadTable()->getTbTransaction($defaultWhere['day']);
            $dataDashboard->nbAMonth = $table->getSalerowTable()->getTbNbArticle($defaultWhere['month']);
            $dataDashboard->nbADay = $table->getSalerowTable()->getTbNbArticle($defaultWhere['day']);
            $dataDashboard->ecMonth = $table->getStorecountTable()->getTbEcarts($ecWhere['month']);
            $dataDashboard->ecDay = $table->getStorecountTable()->getTbEcarts($ecWhere['day']);
            $dataDashboard->acMonth = $table->getSaleheadTable()->getTbAnnulationCaisse($defaultWhere['month']);
            $dataDashboard->acDay = $table->getSaleheadTable()->getTbAnnulationCaisse($defaultWhere['day']);
            $dataDashboard->bqMonth = $table->getStorecountTable()->getTbBanques($ecWhere['month']);
            $dataDashboard->bqDay = $table->getStorecountTable()->getTbBanques($ecWhere['day']);
            $dataDashboard->moMonth = $table->getRhdataTable()->getTbMo($moWhere['month']);
            $dataDashboard->moDay = $table->getRhdataTable()->getTbMo($moWhere['day']);
            $dataDashboard->budgets = $budgets;
            
            return new ViewModel(array(                
                ///////// PERIODE TEXT
                'periodText' => $operationDate->displayPeriodText($request),
                'tabMonthText' => $operationDate->tabMonthText(),

                ///////// STORE
                'store' => $whereQueryBySelection->getStoresNames($request),

                ///////// CHIFFRE D'AFFAIRES
                'caMonth' => $table->getSaleheadTable()->getTbCa($defaultWhere['month']),
                'caDay' => $table->getSaleheadTable()->getTbCa($defaultWhere['day']),

                ///////// TICHET MOYEN
                'tmMonth' => $table->getSaleheadTable()->getTbTmTtc($defaultWhere['month']),
                'tmDay' => $table->getSaleheadTable()->getTbTmTtc($defaultWhere['day']),
                
                ///////// METEO
                'meteoMonth' => $table->getMeteoTable()->getMeteos($meteoWhere['month']),
                'meteoDay' => $table->getMeteoTable()->getMeteo($meteoWhere['day']),
                
                ///////// REPAS
                'mealMonth' => $table->getSaleheadTable()->getTbRepas($defaultWhere['month']),
                'mealDay' => $table->getSaleheadTable()->getTbRepas($defaultWhere['day']),
                
                ///////// TRANSACTION ET VENTE
                'nbTMonth' => $table->getSaleheadTable()->getTbTransaction($defaultWhere['month']),                
                'nbTDay' => $table->getSaleheadTable()->getTbTransaction($defaultWhere['day']),
                
                'nbAMonth' => $table->getSalerowTable()->getTbNbArticle($defaultWhere['month']),
                'nbADay' => $table->getSalerowTable()->getTbNbArticle($defaultWhere['day']),
                
                ///////// ECART CAISSE
                'ecMonth' => $table->getStorecountTable()->getTbEcarts($ecWhere['month']),
                'ecDay' => $table->getStorecountTable()->getTbEcarts($ecWhere['day']),
                
                ///////// ANNULATION CAISSE
                'acMonth' => $table->getSaleheadTable()->getTbAnnulationCaisse($defaultWhere['month']),
                'acDay' => $table->getSaleheadTable()->getTbAnnulationCaisse($defaultWhere['day']),
                
                ///////// BANQUES
                'bqMonth' => $table->getStorecountTable()->getTbBanques($ecWhere['month']),
                'bqDay' => $table->getStorecountTable()->getTbBanques($ecWhere['day']),  
                
                ///////// MO
                'moMonth' => $table->getRhdataTable()->getTbMO($moWhere['month']),
                'moDay' => $table->getRhdataTable()->getTbMO($moWhere['day']),
                
                ///////// BUDGETS
                'budgets' => $budgets,
            ));
        } else {
            return $this->redirect()->toRoute('operationtest/default');
        }
    }
    
    public function scoringAction() {
        $table = new Table($sm = $this->getServiceLocator());
        $operationDate = new OperationDate();
        $operationSession = new Container('operationSession');
        
        $request = $this->getRequest();
        $tableArray = array(
            'marcheStoreTable' => $table->getMarchestoreTable(),
            'marcheTable' => $table->getMarcheTable(),
            'storeTable' => $table->getStoreTable()
        );
        
        $whereQueryBySelection = new WhereQueryBySelection($tableArray);
        
        // CLAUSE WHERE
        $defaultWhere = $whereQueryBySelection->queryForDashboardScoring();
        $otherWhere = $whereQueryBySelection->queryForDashboardScoring('date');
        $meteoWhere = $whereQueryBySelection->queryForDashboardScoringMonthOnly('date');

        // CLAUSE GROUPBY
        $groupby = " GROUP BY saleHead.orderDate";            
        $ecgroupby = " GROUP BY date"; 
        $tmgroupby = " GROUP BY saleHead.orderDate"; 
        $weekData = array();
        $enMonthText = $operationDate->echoMonthtoEn();
        $frMonthText = $operationDate->echoMonthtoShortFr();
        $period = $operationSession->offsetGet('period');
        
        $ca = $table->getSaleheadTable()->getSynthCa($defaultWhere, $groupby); 
        $nbt = $table->getSaleheadTable()->getSynthTransaction($defaultWhere, $groupby);
        $ec = $table->getStorecountTable()->getSynthEcarts($otherWhere, $ecgroupby); 
        $ac = $table->getSaleheadTable()->getSynthAnnulationCaisse($defaultWhere, $groupby);
        $repas = $table->getSaleheadTable()->getSynthRepas($defaultWhere, $groupby);
        foreach($period as $idxm => $month){
            $monthTab = explode(' ', $idxm);
            $year = $monthTab[1];
            $monthText = $enMonthText[$monthTab[0]];
            foreach($month as $idxw => $week){
                foreach($week as $idxd => $day){
                    // CA
                    if(!isset($weekData[$year][$monthText][$idxw]['ca_ttc'])) $weekData[$year][$monthText][$idxw]['ca_ttc'] = 0; 
                    if(!isset($weekData[$year][$monthText][$idxw]['ca_ht'])) $weekData[$year][$monthText][$idxw]['ca_ht'] = 0;
                    foreach($ca as $ca_day){
                        $orderDate = new \DateTime($ca_day['orderDate']);
                        if($orderDate->format('Y')==$year && $orderDate->format('F')==$monthText && $orderDate->format('W')==$idxw && $orderDate->format('Y-m-d')==$day->format('Y-m-d')){
                            $weekData[$year][$monthText][$idxw]['ca_ttc'] += $ca_day['ca_ttc'];
                            $weekData[$year][$monthText][$idxw]['ca_ht'] += $ca_day['ca_ht'];
                        }
                    }
                    // TRANSACTION
                    if(!isset($weekData[$year][$monthText][$idxw]['nbt'])) $weekData[$year][$monthText][$idxw]['nbt'] = 0;                     
                    foreach($nbt as $nbt_day) {
                        $orderDate = new \DateTime($nbt_day['orderDate']);
                        if($orderDate->format('Y')==$year && $orderDate->format('F')==$monthText && $orderDate->format('W')==$idxw && $orderDate->format('Y-m-d')==$day->format('Y-m-d')){
                            $weekData[$year][$monthText][$idxw]['nbt'] += $nbt_day['nbTransaction'];
                        }
                    }                
                    // ECART CAISSE
                    if(!isset($weekData[$year][$monthText][$idxw]['ec'])) $weekData[$year][$monthText][$idxw]['ec'] = 0; 
                    
                    foreach($ec as $ec_day) {
                        $orderDate = new \DateTime($ec_day['date']);
                        if($orderDate->format('Y')==$year && $orderDate->format('F')==$monthText && $orderDate->format('W')==$idxw && $orderDate->format('Y-m-d')==$day->format('Y-m-d')){
                            $weekData[$year][$monthText][$idxw]['ec'] += $ec_day['ec'];
                        }
                    }
                    // ANNULATION CAISSE
                    if(!isset($weekData[$year][$monthText][$idxw]['ac'])) $weekData[$year][$monthText][$idxw]['ac'] = 0; 
                    if(!isset($weekData[$year][$monthText][$idxw]['mac'])) $weekData[$year][$monthText][$idxw]['mac'] = 0;

                    foreach($ac as $ac_day) {
                        $orderDate = new \DateTime($ac_day['orderDate']);
                        if($orderDate->format('Y')==$year && $orderDate->format('F')==$monthText && $orderDate->format('W')==$idxw && $orderDate->format('Y-m-d')==$day->format('Y-m-d')){
                            $weekData[$year][$monthText][$idxw]['ac'] += $ac_day['ac'];
                            $weekData[$year][$monthText][$idxw]['mac'] += $ac_day['montant_ac'];
                        }
                    }
                    // REPAS
                    if(!isset($weekData[$year][$monthText][$idxw]['repas'])) $weekData[$year][$monthText][$idxw]['repas'] = 0; 
                    foreach($repas as $repas_day) {
                        $orderDate = new \DateTime($repas_day['orderDate']);
                        if($orderDate->format('Y')==$year && $orderDate->format('F')==$monthText && $orderDate->format('W')==$idxw && $orderDate->format('Y-m-d')==$day->format('Y-m-d')){
                            $weekData[$year][$monthText][$idxw]['repas'] += $repas_day['repas'];
                        }
                    }
                }
            }
        }
//        echo '<pre>';
//        print_r($weekData);    
//        echo '</pre>';
        
        foreach ($weekData as $y => $year) {
            foreach ($year as $m => $month) {
                $wcount = 1;
                foreach ($month as $weeknum) {
                    if($weeknum['ca_ttc'] !=0 )
                        $weekCattc[$y.'_'.$m.'_'.$wcount] = $weeknum['ca_ttc'];
                    if($weeknum['ca_ht'] !=0 )
                        $weekCaht[$y.'_'.$m.'_'.$wcount] = $weeknum['ca_ht'];
                    if($weeknum['nbt'] !=0 )
                        $weekNbt[$y.'_'.$m.'_'.$wcount] = $weeknum['nbt'];
                    if($weeknum['ec'] !=0 )
                        $weekEc[$y.'_'.$m.'_'.$wcount] = $weeknum['ec'];
                    if($weeknum['ac'] !=0 )
                        $weekAc[$y.'_'.$m.'_'.$wcount] = $weeknum['ac'];
                    if($weeknum['mac'] !=0 )
                        $weekMac[$y.'_'.$m.'_'.$wcount] = $weeknum['mac'];
                    if($weeknum['repas'] !=0 )
                        $weekRepas[$y.'_'.$m.'_'.$wcount] = $weeknum['repas'];
                    $wcount++;
                }
            }
        }
        //var_dump($weekEc);
        foreach($weekCattc as $idx => $w) {
            if($w == max($weekCattc)) {
                $t = explode('_', $idx);
                $maxCattcWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
            if($w == min($weekCattc)) {
                $t = explode('_', $idx);
                $minCattcWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
        }
        foreach($weekCaht as $idx => $w) {
            if($w == max($weekCaht)) {
                $t = explode('_', $idx);
                $maxCahtWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
            if($w == min($weekCaht)) {
                $t = explode('_', $idx);
                $minCahtWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
        }
        foreach($weekNbt as $idx => $w) {
            if($w == max($weekNbt)) {
                $t = explode('_', $idx);
                $maxNbtWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
            if($w == min($weekNbt)) {
                $t = explode('_', $idx);
                $minNbtWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
        }
        foreach($weekEc as $idx => $w) {
            if($w == max($weekEc)) {
                $t = explode('_', $idx);
                $maxEcWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
            if($w == min($weekEc)) {
                $t = explode('_', $idx);
                $minEcWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
        }
        foreach($weekAc as $idx => $w) {
            if($w == max($weekAc)) {
                $t = explode('_', $idx);
                $maxAcWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
            if($w == min($weekAc)) {
                $t = explode('_', $idx);
                $minAcWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
        }
        foreach($weekMac as $idx => $w) {
            if($w == max($weekMac)) {
                $t = explode('_', $idx);
                $maxMacWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
            if($w == min($weekMac)) {
                $t = explode('_', $idx);
                $minMacWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
        }
        foreach($weekRepas as $idx => $w) {
            if($w == max($weekRepas)) {
                $t = explode('_', $idx);
                $maxRepasWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
            if($w == min($weekRepas)) {
                $t = explode('_', $idx);
                $minRepasWeek = $frMonthText[$t[1]].' '.$t[0].'/Semaine '.$t[2];
            }
        }
        $variables = array(
            'meteoMonth' => $table->getMeteoTable()->getMeteos($meteoWhere),
            
            'maxCattc' => max($weekCattc),
            'maxCaht' => max($weekCaht),
            'maxNbt' => max($weekNbt),
            'maxEc' => max($weekEc),
            'maxAc' => max($weekAc),
            'maxMac' => max($weekMac),
            'maxRepas' => max($weekRepas),
            
            'minCattc' => min($weekCattc),
            'minCaht' => min($weekCaht),
            'minNbt' => min($weekNbt),
            'minEc' => min($weekEc),
            'minAc' => min($weekAc),
            'minMac' => min($weekMac),
            'minRepas' => min($weekRepas),
            
            'maxCattcWeek' => $maxCattcWeek,
            'maxCahtWeek' => $maxCahtWeek,
            'maxNbtWeek' => $maxNbtWeek,
            'maxEcWeek' => $maxEcWeek,
            'maxAcWeek' => $maxAcWeek,
            'maxMacWeek' => $maxMacWeek,
            'maxRepasWeek' => $maxRepasWeek,
            
            'minCattcWeek' => $minCattcWeek,
            'minCahtWeek' => $minCahtWeek,
            'minNbtWeek' => $minNbtWeek,
            'minEcWeek' => $minEcWeek,
            'minAcWeek' => $minAcWeek,
            'minMacWeek' => $minMacWeek,
            'minRepasWeek' => $minRepasWeek,
        );
        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        $viewModel->setVariables($variables);
        return $viewModel;
    }
    
    public function getNbOpenDays($orders) {
        $months = array();
        foreach($orders as $order):
            $date = new \DateTime($order['orderDate']);
            @$months[$date->format('Y-m').'-01'] += $order['nbOpenDays'];
        endforeach;
        return $months;
    }
}
?>
